// 采购订单管理API服务
import axios from 'axios'
import { getErrorMessage } from '@/utils/error'
import type {
    CreatePurchaseOrderCommand,
    UpdatePurchaseOrderCommand,
    DeletePurchaseOrderCommand,
    GetPurchaseOrderListQuery,
    GetPurchaseOrderByIdQuery,
    PurchaseOrderListResponse,
    PurchaseOrderDetailResponse,
    OperationResultResponse,
    CreatePurchaseOrderResponse,
    ResultCode,
    SimplePaged,
    InboundRecordRow,
    PaymentRecordRow,
    InvoiceRecordRow,
    InspectionRecordRow,
    ReturnRecordRow,
    ApprovalStepRow,
    OperationRecordRow
} from '@/types/purchaseOrder'

// 创建axios实例 - 直接使用硬编码URL避免配置问题
const purchaseOrderApiClient = axios.create({
    baseURL: 'http://localhost:5000',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 添加请求拦截器
purchaseOrderApiClient.interceptors.request.use(
    (config) => {
        console.log('发送请求:', config.method?.toUpperCase(), config.url, config.params || config.data)
        return config
    },
    (error) => {
        console.error('请求错误:', error)
        return Promise.reject(error)
    }
)

// 添加响应拦截器
purchaseOrderApiClient.interceptors.response.use(
    (response) => {
        console.log('收到响应:', response.status, response.data)
        return response
    },
    (error) => {
        console.error('响应错误:', error.response?.status, error.response?.data || error.message)
        return Promise.reject(error)
    }
)

// 响应拦截器 - 处理响应数据
purchaseOrderApiClient.interceptors.response.use(
    (response) => {
        console.log('收到响应:', response.status, response.data)
        return response
    },
    (error) => {
        console.error('响应错误:', error.response?.status, error.response?.data || error.message)
        if (error.response) {
            // 服务器返回错误状态码
            const { status, data } = error.response
            switch (status) {
                case 400:
                    throw new Error(data?.message || '请求参数错误')
                case 401:
                    throw new Error('未授权，请重新登录')
                case 403:
                    throw new Error('禁止访问')
                case 404:
                    throw new Error('请求的资源不存在')
                case 500:
                    throw new Error(data?.message || '服务器内部错误')
                default:
                    throw new Error(data?.message || `请求失败 (${status})`)
            }
        } else if (error.request) {
            // 请求已发出但没有收到响应
            throw new Error('网络连接失败，请检查网络设置')
        } else {
            // 请求配置错误
            throw new Error('请求配置错误')
        }
    }
)

function normalizeApiResult<T>(raw: any): { code: ResultCode; message: string; data: T } {
    try {
        // 处理axios响应结构
        const responseData = raw?.data || raw
        return {
            code: responseData?.code ?? responseData?.Code ?? ResultCode.Fail,
            message: responseData?.message ?? responseData?.Message ?? '',
            data: responseData?.data ?? responseData?.Data
        }
    } catch (error) {
        console.error('标准化API结果时出错:', error)
        return {
            code: ResultCode.Fail,
            message: '数据处理失败',
            data: null as any
        }
    }
}

// 采购订单管理API
export const purchaseOrderApi = {
    /**
     * 获取采购订单列表
     * @param params 查询参数
     * @returns 采购订单列表响应
     */
    async getPurchaseOrderList(params: GetPurchaseOrderListQuery): Promise<PurchaseOrderListResponse> {
        try {
            const query = {
                PageIndex: params.pageIndex,
                PageSize: params.pageSize,
                OrderSubject: params.orderSubject,
                PurchaseOrderNumber: params.purchaseOrderNumber,
                SupplierId: params.supplierId,
                OrderStatus: params.orderStatus,
                PurchaseDateStart: params.purchaseDateStart,
                PurchaseDateEnd: params.purchaseDateEnd,
                CreatedBy: params.createdBy
            }

            console.log('发送查询参数:', query)
            const raw = await purchaseOrderApiClient.get('/api/PurchaseOrder/list', { params: query })
            console.log('API原始响应:', raw)

            const normalizedOuter = normalizeApiResult<any>(raw)
            console.log('标准化后的响应:', normalizedOuter)

            const inner = normalizedOuter.data || {}
            const pageData = inner.pageData ?? inner.PageData ?? []
            const totalCount = inner.totalCount ?? inner.TotalCount ?? 0
            const pageIndex = inner.pageIndex ?? inner.PageIndex ?? query.PageIndex
            const pageSize = inner.pageSize ?? inner.PageSize ?? query.PageSize
            const totalPages = inner.totalPages ?? inner.TotalPages ?? Math.ceil(totalCount / pageSize)

            console.log('处理后的数据:', { pageData, totalCount, pageIndex, pageSize, totalPages })

            return {
                code: normalizedOuter.code,
                message: normalizedOuter.message,
                data: {
                    pageData,
                    totalCount,
                    pageIndex,
                    pageSize,
                    totalPages
                }
            }
        } catch (error) {
            console.error('获取采购订单列表失败:', error)
            throw new Error(getErrorMessage(error))
        }
    },

    /**
     * 根据ID获取采购订单详情
     * @param id 采购订单ID
     * @returns 采购订单详情响应
     */
    async getPurchaseOrderById(id: number): Promise<PurchaseOrderDetailResponse> {
        try {
            const raw = await purchaseOrderApiClient.get(`/api/PurchaseOrder/${id}`)
            const normalized = normalizeApiResult<any>(raw)
            return {
                code: normalized.code,
                message: normalized.message,
                data: normalized.data
            }
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    },

    /**
 * 创建采购订单
 * @param command 创建采购订单命令
 * @returns 创建结果响应
 */
    async createPurchaseOrder(command: CreatePurchaseOrderCommand): Promise<CreatePurchaseOrderResponse> {
        try {
            const raw = await purchaseOrderApiClient.post('/api/PurchaseOrder', command)
            const normalized = normalizeApiResult<number>(raw)
            return {
                code: normalized.code,
                message: normalized.message,
                data: normalized.data
            }
        } catch (error) {
            console.error('创建采购订单失败，请求体为:', command)
            console.error('错误详情:', error)
            throw new Error(getErrorMessage(error))
        }
    },

    /**
 * 更新采购订单
 * @param command 更新采购订单命令
 * @returns 操作结果响应
 */
    async updatePurchaseOrder(command: UpdatePurchaseOrderCommand): Promise<OperationResultResponse> {
        try {
            const raw = await purchaseOrderApiClient.put('/api/PurchaseOrder', command)
            const normalized = normalizeApiResult<boolean>(raw)
            return {
                code: normalized.code,
                message: normalized.message,
                data: normalized.data
            }
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    },

    /**
 * 删除采购订单
 * @param id 采购订单ID
 * @returns 操作结果响应
 */
    async deletePurchaseOrder(id: number): Promise<OperationResultResponse> {
        try {
            const raw = await purchaseOrderApiClient.delete(`/api/PurchaseOrder/${id}`)
            const normalized = normalizeApiResult<boolean>(raw)
            return {
                code: normalized.code,
                message: normalized.message,
                data: normalized.data
            }
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    },

    // 详情各记录
    async getInboundRecords(id: number, pageIndex = 1, pageSize = 5) {
        const raw = await purchaseOrderApiClient.get(`/api/PurchaseOrder/${id}/inbounds`, { params: { PageIndex: pageIndex, PageSize: pageSize } })
        const normalized = normalizeApiResult<SimplePaged<InboundRecordRow>>(raw)
        return normalized
    },

    async getPaymentRecords(id: number, pageIndex = 1, pageSize = 5) {
        const raw = await purchaseOrderApiClient.get(`/api/PurchaseOrder/${id}/payments`, { params: { PageIndex: pageIndex, PageSize: pageSize } })
        const normalized = normalizeApiResult<SimplePaged<PaymentRecordRow>>(raw)
        return normalized
    },

    async getInvoiceRecords(id: number, pageIndex = 1, pageSize = 5) {
        const raw = await purchaseOrderApiClient.get(`/api/PurchaseOrder/${id}/invoices`, { params: { PageIndex: pageIndex, PageSize: pageSize } })
        const normalized = normalizeApiResult<SimplePaged<InvoiceRecordRow>>(raw)
        return normalized
    },

    async getInspectionRecords(id: number, pageIndex = 1, pageSize = 5) {
        const raw = await purchaseOrderApiClient.get(`/api/PurchaseOrder/${id}/inspections`, { params: { PageIndex: pageIndex, PageSize: pageSize } })
        const normalized = normalizeApiResult<SimplePaged<InspectionRecordRow>>(raw)
        return normalized
    },

    async getReturnRecords(id: number, pageIndex = 1, pageSize = 5) {
        const raw = await purchaseOrderApiClient.get(`/api/PurchaseOrder/${id}/returns`, { params: { PageIndex: pageIndex, PageSize: pageSize } })
        const normalized = normalizeApiResult<SimplePaged<ReturnRecordRow>>(raw)
        return normalized
    },

    async getApprovalRecords(id: number) {
        const raw = await purchaseOrderApiClient.get(`/api/PurchaseOrder/${id}/approvals`)
        const normalized = normalizeApiResult<{ flow: { nodes: string[] }, steps: ApprovalStepRow[] }>(raw)
        return normalized
    },

    async getOperationRecords(id: number, pageIndex = 1, pageSize = 5) {
        const raw = await purchaseOrderApiClient.get(`/api/PurchaseOrder/${id}/operations`, { params: { PageIndex: pageIndex, PageSize: pageSize } })
        const normalized = normalizeApiResult<SimplePaged<OperationRecordRow>>(raw)
        return normalized
    },

    // 审批流
    async submitPurchaseOrder(id: number) {
        const raw = await purchaseOrderApiClient.post(`/api/PurchaseOrder/${id}/submit`)
        return normalizeApiResult<boolean>(raw)
    },
    async approvePurchaseOrder(id: number, comments?: string) {
        const raw = await purchaseOrderApiClient.post(`/api/PurchaseOrder/${id}/approve`, { comments })
        return normalizeApiResult<boolean>(raw)
    },
    async rejectPurchaseOrder(id: number, reason?: string, rejectToPreviousLevel = false, rejectToApplicant = false) {
        const raw = await purchaseOrderApiClient.post(`/api/PurchaseOrder/${id}/reject`, { reason, rejectToPreviousLevel, rejectToApplicant })
        return normalizeApiResult<boolean>(raw)
    },

    /**
     * 插入测试数据
     * @returns 操作结果响应
     */
    async insertTestData(): Promise<OperationResultResponse> {
        try {
            console.log('开始插入测试数据...')
            const raw = await purchaseOrderApiClient.post('/api/PurchaseOrder/insert-test-data')
            const normalized = normalizeApiResult<boolean>(raw)
            return {
                code: normalized.code,
                message: normalized.message,
                data: normalized.data
            }
        } catch (error) {
            console.error('插入测试数据失败:', error)
            throw new Error(getErrorMessage(error))
        }
    }
} 